package net;

import gui.FriendList;
import gui.UserUI;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import util.Protocol;

public class ReceiveInformation implements Runnable
{
	boolean isok;
	
	static HashMap<String,JFrame> clientPool;
	
	Protocol protocol = new Protocol();
	
	static
	{
		clientPool = new HashMap<String,JFrame>();
	}
	BackClient backClient = new BackClient();
	
	public ReceiveInformation() 
	{
	}
	
	public void addthisWindows(String windowname,JFrame jframe)
	{
		JFrame thisframe = clientPool.put(windowname,jframe);
	}
	
	public JFrame returnthisWindows(String windowname)
	{
		JFrame thisframe = clientPool.get(windowname);
		return thisframe;
	}
	
	public boolean addFriendIsok()
	{
		return isok;
	}
	
	public void run()
	{
		String str = backClient.ReseiveFriendMassage();
		String[] content = str.split(":");
		String head = content[0];
		
		if(head.equals("AddFriendrequest"))
		{
			String[] name = content[1].split(",");
			String friendID = name[0];
			String nickname = name[1];
			
			int choose = JOptionPane.showConfirmDialog(null,friendID+"想加您为好友。");
			if(choose == JOptionPane.YES_OPTION)
			{
				String addmassage = protocol.getAddFriendOkMessage(nickname, friendID);
				backClient.SendMassage(addmassage);
				FriendList friendList = (FriendList)returnthisWindows("friendlist");
				friendList.setNewFriend(friendID);
			}
			if(choose == JOptionPane.NO_OPTION)
			{
				String addmassage = protocol.getAddFriendNoMessage(nickname, friendID);
				backClient.SendMassage(addmassage);
			}
		}
		
		if(head.equals("NotExist"))
		{
			FriendList friendList = (FriendList)returnthisWindows("friendlist");
			JOptionPane.showMessageDialog(null,"查询好友不存在");
		}
		
		if(head.equals("Refuse"))
		{
			JOptionPane.showMessageDialog(null,"对方拒绝添加您为好友");
		}
		
		if(head.equals("addFriendok"))
		{
			String[] name = content[1].split(",");
			String friendID = name[0];
			String nickname = name[1];
			System.out.println(nickname+173);
			
			String addmassage = protocol.getAddFriendOkMessage(nickname, friendID);
			backClient.SendMassage(addmassage);
			JOptionPane.showMessageDialog(null,"发送成功");
			FriendList friendList = (FriendList)returnthisWindows("friendlist");
			friendList.setNewFriend(friendID);
		}
		if(head.equals("Newmassage"))
		{
			String friendID = content[1];
			String context = content[2];
			String nickname = content[3];
			UserUI frame = (UserUI) returnthisWindows(friendID);
			if(frame==null)
			{
				UserUI ui = new UserUI();
				ui.getfrinedID(friendID);
				ui.setNickname(nickname);
				ui.setVisible(true);
				ui.setConversation(friendID,context);
				addthisWindows(friendID,ui);
			}
			else
			{
				frame.setConversation(friendID, context);
			}
		}
	}    
}
	

